package hn.cch.aspect;


import hn.cch.constant.Common;
import hn.cch.constant.Digit;
import hn.cch.constant.Letter;
import hn.cch.server.api.HttpApi;
import hn.cch.server.request.HttpReqMsg;
import hn.cch.server.response.DigitRespMsg;
import hn.cch.server.response.HttpRespMsg;
import hn.cch.server.response.LetterRespMsg;
import hn.cch.bean.Bean;
import hn.cch.util.JsonUtil;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class HttpAop {

    private Logger logger = LoggerFactory.getLogger(HttpAop.class);

    public byte[] aop(String string, byte[] bytes){

        HttpReqMsg httpReqMsg = new HttpReqMsg();
        HttpRespMsg httpRespMsg = new HttpRespMsg();

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(string);
        httpReqMsg.getGet().setPath(queryStringDecoder.path());

        Map<String, List<String>> params = queryStringDecoder.parameters();
        try {
            //参数校验和赋值
            httpReqMsg.getGet().setType(uriAop(params, Common.TYPE));
            httpReqMsg.getGet().setUser(uriAop(params, Common.USER));
            httpReqMsg.getGet().setHash(uriAop(params, Common.HASH));
        }catch (RuntimeException e){
            //根据path判断返回码类型并返回参数错误
            if (Common.digits.contains(httpReqMsg.getGet().getPath())){//数字
                DigitRespMsg digitRespMsg = new DigitRespMsg();
                digitRespMsg.setCode(Digit.PARAM);
                digitRespMsg.setContent(null);
                return JsonUtil.toBytes(digitRespMsg);
            }
            if (Common.letters.contains(httpReqMsg.getGet().getPath())){//字母
                LetterRespMsg letterRespMsg = new LetterRespMsg();
                letterRespMsg.setCode(Letter.PARAM);
                letterRespMsg.setContent(null);
                return JsonUtil.toBytes(letterRespMsg);
            }
            //无法判断返回码类型
            logger.error("digits or letters");
            httpRespMsg.setInfo("digits or letters");
            httpRespMsg.setContent(null);
            return JsonUtil.toBytes(httpRespMsg);
        }


//        hash
//        格式：path|type
        String api = httpReqMsg.getGet().getPath() + "|" + httpReqMsg.getGet().getType();
        HttpApi httpApi = (HttpApi) Bean.getBean(api);
        return httpApi.api(httpReqMsg, bytes);


    }

    private String uriAop(Map<String, List<String>> params, String string) throws RuntimeException {
        if(params.containsKey(string)){
            String param = params.get(string).get(0);//默认获取下标为0的第一个为有效参数
            if (!param.equals("")){
                return params.get(string).get(0);
            }
        }
        logger.error(string + " error");
        throw new RuntimeException(string + " null");
//        return null;

    }
}
